package com.wuwei.elearning.question.controller;


import com.wuwei.elearning.service.CacheService;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.question.domain.Subject;
import com.wuwei.elearning.question.mapper.SubjectMapper;
import com.wuwei.elearning.question.mapper.UserRelationSubjectMapper;
import com.wuwei.elearning.question.service.UserRelationSubjectService;
import com.wuwei.elearning.utils.MinioUtil;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2025-03-13
 */
@RestController
@CrossOrigin
@RequestMapping("/elearning/userRelationSubject")
public class UserRelationSubjectController {

    @Resource
    private UserRelationSubjectService userRelationSubjectService;
    @Autowired
    private UserRelationSubjectMapper userRelationSubjectMapper;
    @Autowired
    private SubjectMapper subjectMapper;

    /**
     * 根据subjectId去user_relation_subject找出所有subject_id的数据，返回其account，一个Long类型的数组
     * @param subjectId
     * @return
     */
    @GetMapping("getUserAccountBySubjectId/{subjectId}")
    public Result<List<Long>> getUserAccountBySubjectId(@PathVariable("subjectId") Long subjectId) {
        // 查找所有account
        List<Long> accounts =  userRelationSubjectMapper.getAccountsBySubjectIds(subjectId);
        return Result.ok(accounts);
    }

    @Resource
    private CacheService cacheService;

    @Resource
    private MinioUtil minioUtil;

    /**
     * 根据account去user_relation_subject表查询所有相关课程
     * 该请求要返回在有效期内的课程
     * 这里只查询根数据
     * @return
     */
    @GetMapping("getMySubjects")
    private Result<List<Subject>> getMySubjects (HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        List<Long> subjectIds = userRelationSubjectMapper.getSubjectsByAccount(account);
        List<Subject> res = new ArrayList<>();
        if (subjectIds.isEmpty()) {
            return Result.ok(res);
        } else {

            res = subjectMapper.myBatchSelectWithDateAndOnService(subjectIds);
            // 创建一个Set来存储所有的ID，用于快速查找
            Set<Long> allIds = res.stream()
                    .map(Subject::getId)
                    .collect(Collectors.toSet());

            // 过滤出根节点：
            // 1. parentId 为 null 的节点
            // 2. parentId 不在当前列表中的节点
            List<Subject> rootSubjects = res.stream()
                    .filter(subject ->
                            subject.getParentId() == null ||
                                    !allIds.contains(subject.getParentId()))
                    .collect(Collectors.toList());

            for (Subject subject : rootSubjects) {
                String cover = subject.getCover();
                // 构建Redis键
                String redisKey = Constant.MINIO_COVER + cover;
                // 尝试从Redis获取
                String serviceCover = cacheService.getCover(cover, redisKey);
                subject.setCover(serviceCover);
            }
            return Result.ok(rootSubjects);
        }
    }



}

